//
//  HEAIChatInputView.m
//  HealthFamily
//
//  Created by 吴欧 on 2020/11/22.
//  Copyright © 2020 honglutec. All rights reserved.
//

#import "HEAIChatInputView.h"

@interface HEAIChatInputView ()

@property(nonatomic, strong) QMUITextView *textView;
@property(nonatomic, strong) UIView *self;
@property(nonatomic, strong) UIView *tabbarWarp;
@property(nonatomic, strong) UIView *voiceWarp;
@property(nonatomic, strong) UIButton *yuyinView;

@property(nonatomic, assign) BOOL fristInto;
@property(nonatomic, assign) CGFloat transformY;

@property(nonatomic, assign) CGFloat panelheight;

@end

@implementation HEAIChatInputView

- (instancetype)initWithFrame:(CGRect)frame {
    if (self = [super initWithFrame:frame]) {
        
        self.qmui_borderPosition = QMUIViewBorderPositionTop;
        self.qmui_borderWidth = 1;
        self.qmui_borderColor = CSplitLineColor;
        
        [self initUI];
        
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillChangeFrameNotify:) name:UIKeyboardWillChangeFrameNotification object:nil];

    }
    return self;
}


- (void)initUI {
  
 
  
  UIView *tabbarWarp = [UIView new];
  _tabbarWarp = tabbarWarp;
  [self addSubview:tabbarWarp];
  
  
  [tabbarWarp mas_makeConstraints:^(MASConstraintMaker *make) {
      make.top.equalTo(self);
      make.height.equalTo(@49);
      make.left.right.equalTo(self);
  }];
 
  
  // 语音
  UIButton *yuyinView = [UIButton buttonWithType:UIButtonTypeCustom];
  [yuyinView setImage:IMAGE_NAMED(@"voice") forState:UIControlStateNormal];
  [tabbarWarp addSubview:yuyinView];
  [yuyinView addTarget:self action:@selector(voiceClick:) forControlEvents:UIControlEventTouchUpInside];
  _yuyinView = yuyinView;
  
  //
  UIView *nomralView = [UIView new];
  [self addSubview:nomralView];
  
  // 咨询记录
  UIImageView *reportView = [UIImageView new];
  reportView.image = IMAGE_NAMED(@"service_his");
  reportView.contentMode = UIViewContentModeScaleAspectFit;
  [nomralView addSubview:reportView];
  
  
  UIImageView *addView = [UIImageView new];
  addView.image = IMAGE_NAMED(@"add_media");
  addView.contentMode = UIViewContentModeScaleAspectFit;
  [nomralView addSubview:addView];
  
  
  // 输入框
  _textView = [QMUITextView  new];
  _textView.placeholder = @"开始免费咨询";
  _textView.placeholderColor = CNavSubTitleColor; // 自定义 placeholder 的颜色
  _textView.placeholderMargins = UIEdgeInsetsMake(0, 7, 0, 7);
  _textView.typingAttributes = @{NSFontAttributeName: UIFontMake(16),
                                     NSParagraphStyleAttributeName: [NSMutableParagraphStyle qmui_paragraphStyleWithLineHeight:20]
  };
  _textView.backgroundColor = CSplitLineColor;
  _textView.layer.cornerRadius = 4;
  [_textView setDelegate:self];
  _textView.text = @"cdscds";
  [tabbarWarp addSubview:_textView];
  
  [_textView mas_makeConstraints:^(MASConstraintMaker *make) {
      make.top.equalTo(tabbarWarp).mas_offset(6);
      make.left.equalTo(yuyinView.mas_right).offset(10);
      make.right.equalTo(nomralView.mas_left).offset(-10);
      make.bottom.equalTo(tabbarWarp).mas_offset(-6);
  }];
  
  [yuyinView mas_makeConstraints:^(MASConstraintMaker *make) {
      make.centerY.equalTo(tabbarWarp);
      make.left.equalTo(tabbarWarp).offset(10);
      make.width.equalTo(@25);
      make.height.equalTo(@27);
  }];
  
  
  [nomralView mas_makeConstraints:^(MASConstraintMaker *make) {
      make.centerY.equalTo(tabbarWarp);
      make.right.equalTo(tabbarWarp).offset(-10);
      make.width.mas_offset(32 * 2 + 10);
  }];
  
  NSArray *arr1 = @[reportView, addView];
  [arr1 mas_makeConstraints:^(MASConstraintMaker *make) {
      make.top.equalTo(nomralView).offset(5);
      make.bottom.equalTo(nomralView).offset(-5);
  }];
  [arr1 mas_distributeViewsAlongAxis:MASAxisTypeHorizontal withFixedSpacing:10 leadSpacing:0 tailSpacing:0];
}


- (void)voiceClick:(UIButton *)sender {
  
  sender.selected = !sender.selected;
  CGFloat h = self.top - ZXNavBarHeight;

  [self addSubview: self.voiceWarp];
  
  if (sender.selected) {
      [self.superview setNeedsUpdateConstraints];
      [self.superview updateConstraintsIfNeeded];
      
      [self.voiceWarp mas_makeConstraints:^(MASConstraintMaker *make) {
          make.top.equalTo(_tabbarWarp.mas_bottom);
          make.left.right.equalTo(self);
          make.width.mas_offset(KScreenWidth);
          make.height.mas_offset(_panelheight);
      }];
      // 立即绘制
      [self.voiceWarp.superview layoutIfNeeded];
      
      [UIView animateWithDuration:.3 animations:^{
          self.voiceWarp.alpha = 1;

          
          self.tableView.frame = CGRectMake(0, ZXNavBarHeight, KScreenWidth, h - _panelheight );

          [self mas_updateConstraints:^(MASConstraintMaker *make) {
              make.height.mas_equalTo(self.tabbarWarp.height + _panelheight);
          }];
          [self.superview layoutIfNeeded];
      }];
  }else {
      [self hideViocePanel];
  }
}

- (UIView *)voiceWarp {
  if (!_voiceWarp) {
      _voiceWarp = [UIView new];
      
      QMUIButton *check = [[QMUIButton alloc] init];
      check.imagePosition = QMUIButtonImagePositionTop;// 将图片位置改为在文字下方
      check.tintColorAdjustsTitleAndImage = CNavSubTitleColor;
      check.adjustsImageTintColorAutomatically = NO;
      check.spacingBetweenImageAndTitle = 10;
      [check setImage:UIImageMake(@"input_record") forState:UIControlStateNormal];
      [check setTitle:@"按住我震动后语音输入" forState:UIControlStateNormal];
      check.titleLabel.font = DYFont(15);
      [_voiceWarp addSubview:check];
      
      [check mas_makeConstraints:^(MASConstraintMaker *make) {
          make.top.equalTo(_voiceWarp);
          make.centerY.equalTo(_voiceWarp);
          make.centerX.equalTo(_voiceWarp);
          make.bottom.equalTo(_voiceWarp);
      }];

  }
  return _voiceWarp;
}

 
  
/**
*  点击了return按钮(键盘最右下角的按钮)就会调用
*/
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
  return YES;
}

/**
*  当键盘改变了frame(位置和尺寸)的时候调用
*/
- (void)keyboardWillChangeFrameNotify:(NSNotification*)notify {
  CGFloat tabbarHeight = self.height + KSafeTabbarHeight;
  _fristInto = NO;

  
  // 0.取出键盘动画的时间
  CGFloat duration = [notify.userInfo[UIKeyboardAnimationDurationUserInfoKey] doubleValue];
  // 1.取得键盘最后的frame
  CGRect keyboardFrame = [notify.userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue];
  
  CGFloat keyBordOriginY = keyboardFrame.origin.y;
  BOOL iOS7 = ([[[UIDevice currentDevice] systemVersion] doubleValue] < 8.0);
  UIInterfaceOrientation orientation =
  [[UIApplication sharedApplication] statusBarOrientation];
  if (iOS7 && (orientation == UIDeviceOrientationLandscapeLeft
               || orientation == UIDeviceOrientationLandscapeRight)) {
      keyBordOriginY = keyboardFrame.origin.x + keyboardFrame.size.width;
  }

  // 2.计算控制器的view需要平移的距离
  CGFloat transformY = keyBordOriginY - KScreenHeight;
  _transformY = transformY;
  
  // 3.执行动画
  [UIView animateWithDuration:duration animations:^{
      self.tableView.frame = CGRectMake(0, ZXNavBarHeight, KScreenWidth, KScreenHeight - ZXNavBarHeight - tabbarHeight + transformY );

      self.transform = CGAffineTransformMakeTranslation(0, transformY);
//        [self scrollTableViewToBottom];

      [self scrollToBottom];
  }];
}

- (void)scrollToBottom
{
  CGFloat yOffset = 0; //设置要滚动的位置 0最顶部 CGFLOAT_MAX最底部
  if (self.tableView.contentSize.height > self.tableView.bounds.size.height) {
      yOffset = self.tableView.contentSize.height - self.tableView.bounds.size.height;
  }
  [self.tableView setContentOffset:CGPointMake(0, yOffset) animated: !_fristInto];
}
 

#pragma mark - <QMUITextViewDelegate>
// 实现这个 delegate 方法就可以实现自增高
- (void)textView:(QMUITextView *)textView newHeightAfterTextChanged:(CGFloat)height {

  CGFloat he = height + 6 *2;
  CGFloat offest = he - _tabbarWarp.height;

  [self.superview setNeedsUpdateConstraints];
  [self.superview updateConstraintsIfNeeded];
  if (he > self.height) {
      
      [_tabbarWarp mas_updateConstraints:^(MASConstraintMaker *make) {
          make.height.mas_offset(he);
      }];
      
      [self mas_updateConstraints:^(MASConstraintMaker *make) {
          make.height.mas_offset(self.height + offest);
      }];
  }else {
      if (he > 49) {
          [_tabbarWarp mas_updateConstraints:^(MASConstraintMaker *make) {
              make.height.mas_offset(he);
          }];
          
          [self mas_updateConstraints:^(MASConstraintMaker *make) {
              make.height.mas_offset(self.height + offest);
          }];
      }else {
          [_tabbarWarp mas_updateConstraints:^(MASConstraintMaker *make) {
              make.height.mas_offset(49);
          }];
          
          [self mas_updateConstraints:^(MASConstraintMaker *make) {
              make.height.mas_offset( _yuyinView.isSelected ? (_panelheight + 49) : 49);
          }];
      }
  }
  [self.superview layoutIfNeeded];

  self.tableView.frame = CGRectMake(0, ZXNavBarHeight, KScreenWidth, self.top - ZXNavBarHeight);
}

- (void)textView:(QMUITextView *)textView didPreventTextChangeInRange:(NSRange)range replacementText:(NSString *)replacementText {
  [Dialog toast:[NSString stringWithFormat:@"文字不能超过 %@ 个字符", @(textView.maximumTextLength)] delay:2.0];
}

- (void)textViewDidChange:(UITextView *)textView {

}


-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
  [_textView resignFirstResponder];
}

 

- (void)hideViocePanel {
  
  CGFloat h = self.top - ZXNavBarHeight;

  // 告诉self约束需要更新
  [self.superview setNeedsUpdateConstraints];
  // 调用此方法告诉self检测是否需要更新约束，若需要则更新，下面添加动画效果才起作用
  [self.superview updateConstraintsIfNeeded];

  [UIView animateWithDuration:.3 animations:^{
      self.voiceWarp.alpha = 0;
      
      self.tableView.frame = CGRectMake(0, ZXNavBarHeight, KScreenWidth, h + _panelheight);

      [self mas_updateConstraints:^(MASConstraintMaker *make) {
          make.height.mas_equalTo(self.tabbarWarp.height);
      }];
      //告知父类控件绘制，不添加注释的这两行的代码无法生效
      [self.superview layoutIfNeeded];
  } completion:^(BOOL finished) {
      [self.voiceWarp removeFromSuperview];
  }];
}


@end
